const { ipcMain, dialog } = require('electron');
const fs = require('fs');
const Build = require('./common/Build');

function createIPC({ app, mainWindow }) {
  // const filename = `${app.getPath('userData')}/content.txt`;
  // console.log('wxf', filename);
  // const loadContent = async () => {
  //   return fs.existsSync(filename) ? fs.readFileSync(filename, 'utf8') : '';
  // };
  // const saveContent = async (content) => {
  //   fs.writeFileSync(filename, content, 'utf8');
  // };
  // ipcMain.on('saveContent', (e, content) => {
  //   console.log(content);
  //   saveContent(content);
  // });
  // async function handleFileOpen() {
  //   const { canceled, filePaths } = await dialog.showOpenDialog();
  //   if (!canceled) {
  //     console.log(filePaths[0]);
  //     return filePaths[0];
  //   }
  // }
  // ipcMain.handle('dialog:openFile', handleFileOpen);
  // let i = 1;
  // setInterval(() => {
  //   mainWindow.webContents.send('updateCounter', i++);
  // }, 1000);

  const basePath = app.getPath('userData');

  function sendOverview() {
    mainWindow.webContents.send('overview:update', {});
  }

  ipcMain.on('download:doc', (e, content) => {
    console.log(content);
    new Build({
      entry: content,
      rule: '',
      cookie: '',
      replace: false,
      basePath,
      onUpdate: (msg) => {
        console.log('更新');
        mainWindow.webContents.send('download:update', msg);
      },
      onEnd: (msg) => {
        console.log('结束');
        mainWindow.webContents.send('download:end', msg);
        // todo: 保存概览信息
        // 前端发送概览信息
      }
    });
  });
}

module.exports = createIPC;
